<?php

namespace app\common\model\banxi\organization;

use app\common\enums\QuotaBusinessTypeEnum;
use app\common\model\common\BaseModel;
use app\common\service\organization\OrganizationDataService;
use app\common\service\SnowflakeService;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/**
 * 机构用户海报
 */
class OrganizationQuotaRw extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_organization_quota_rw';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'businessTypeCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'tradeType' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getBusinessTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['businessType'] ?? '');
        return (new QuotaBusinessTypeEnum())->getDescription($value) ?? '';
    }



    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------


    public function updateAccount($trade)
    {
        $rwId = $trade['id'] ?? 0;
        if (!$rwId) {
            $snowflakeService = new SnowflakeService(1, 1);
            $rwId = $snowflakeService->nextId();
            $trade['id'] = $rwId;
        }
        $organizationId = $trade['organizationId'];
        $businessType = $trade['businessType'];
        $tradeType = (new QuotaBusinessTypeEnum())->getTradeType($businessType);
        $trade['tradeType'] = $tradeType;
        $organizationDataService = new OrganizationDataService();
        $organizationData = $organizationDataService->getByOrganization($organizationId);
        $beforeValue = $organizationData['partnerQuotaNum'];
        if ($tradeType) {
            //入账
            $afterValue = $beforeValue + $trade['value'];
        } else {
            //出账
            $afterValue = $beforeValue - $trade['value'];
            if ($afterValue < 0) {
                throw new ValidateException('可用名额不足');
            }
        }
        $cnt = $organizationDataService->updateQuotaNum($organizationId, $beforeValue, $afterValue);
        if (!$cnt) {
            throw new ValidateException('更新申请名额失败');
        }
        $trade['beforeValue'] = $beforeValue;
        $trade['afterValue'] = $afterValue;
        $this->save($trade);
        return true;
    }

    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,managerName,name');
            }
        ])->where($where)
            ->order(['id' => 'desc'])
            ->paginate([
                'page' => $page,
                'list_rows' => $limit
            ])->each(function ($item) {
                if ($item['organizationId'] == 0) {
                    $organization = new Organization();
                    $item['organizationBaseInfo'] = $organization->getOrganizationInfo();
                }
            });
    }

    public function getInfo(array $where)
    {
        $info = $this->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,managerName,name');
            }
        ])->where($where)
            ->find();
        if (!$info) {
            return [];
        }
        if ($info['organizationId'] == 0) {
            $organization = new Organization();
            $info['organizationBaseInfo'] = $organization->getOrganizationInfo();
        }
        return $info;
    }

    public function getExportExcel(array $where)
    {
        return $this->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,name,managerName');
            }])
            ->where($where)
            ->order(['id' => 'asc'])
            ->select();
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------
    public function organizationBaseInfo()
    {
        return $this->hasOne(Organization::class, 'id', 'organizationId');
    }

}